#include "prim.h"
#include "calc.h"

#define ONES8 (((uint64_t)1 << 8) - 1)

int i2osp(octet_string *s, const big_integer *x) {
	for (int i = NUM_DIGITS / 2; i < NUM_DIGITS; ++i) {
		if (x->digits[i] != 0) {
			return 1;
		}
	}
	int idx = 0;
	for (int i = NUM_DIGITS / 2 - 1; i >= 0; --i) {
		for (int j = 3; j >= 0; --j) {
			s->octets[idx++] = (uint8_t)(x->digits[i] >> (j * 8) & ONES8);
		}
	}
	return 0;
}

int os2ip(big_integer *x, const octet_string *s) {
	clear_big_integer(x);
	int idx = 0;
	for (int i = NUM_DIGITS / 2 - 1; i >= 0; --i) {
		for (int j = 3; j >= 0; --j) {
			x->digits[i] |= ((uint64_t)s->octets[idx++] << (j * 8));
		}
	}
	return 0;
}

int rsaep(big_integer *c, const big_integer *n, const big_integer *e, const big_integer *m) {
	for (int i = NUM_DIGITS / 2; i < NUM_DIGITS; ++i) {
		if (m->digits[i] != 0) {
			return 1;
		}
	}
	bi_mpow(c, m, e, n);
	return 0;
}

int rsadp(big_integer *m, const big_integer *n, const big_integer *d, const big_integer *c) {
	for (int i = NUM_DIGITS / 2; i < NUM_DIGITS; ++i) {
		if (c->digits[i] != 0) {
			return 1;
		}
	}
	bi_mpow(m, c, d, n);
	return 0;
}
